from fastapi import APIRouter, HTTPException, Depends
from typing import List
from sqlalchemy.orm import Session
from schema import Farming_Operation_schema
from controller import Farming_Operation_controller
from database.db_init import get_db


router = APIRouter()


@router.post("/Farming_Operation", response_model=Farming_Operation_schema.Farming_operation, tags=["Farming_Operation"])
async def create_Farming_Operation(Farming_Operation: Farming_Operation_schema.Farming_operation, db: Session = Depends(get_db)):
    return Farming_Operation_controller.create_Farming_Operation(db, Farming_Operation)


@router.get("/Farming_Operation/{ID}", response_model=Farming_Operation_schema.Farming_operation, tags=["Farming_Operation"])
async def get_Farming_Operation(ID: int, db: Session = Depends(get_db)):
    db_Farming_Operation = Farming_Operation_controller.get_Farming_Operation(db, ID)
    if db_Farming_Operation is None:
        raise HTTPException(status_code=404, detail="Farming_Operation not found")
    return db_Farming_Operation


@router.get("/Farming_Operation", response_model=List[Farming_Operation_schema.Farming_operation], tags=["Farming_Operation"])
async def get_all_Farming_Operation(db: Session = Depends(get_db)):
    all_db_Farming_Operation = Farming_Operation_controller.get_all_Farming_Operation(db)
    if all_db_Farming_Operation is None:
        raise HTTPException(status_code=404, detail="0 Farming_Operation found, empty table")
    return all_db_Farming_Operation


@router.put("/Farming_Operation/{ID}", tags=["Farming_Operation"])
async def update_Farming_Operation(ID: int, field_name: str, field_value: str, db: Session = Depends(get_db)):
    try:
        db_Farming_Operation = Farming_Operation_controller.update_Farming_Operation(db, ID, field_name, field_value)
        if db_Farming_Operation is None:
            raise HTTPException(status_code=404, detail="Farming_Operation not found")
        return db_Farming_Operation
    except ValueError as error:
        raise HTTPException(status_code=400, detail=str(error))


@router.delete("/Farming_Operation/{ID}", tags=["Farming_Operation"])
async def delete_Farming_Operation(ID: int, db: Session = Depends(get_db)):
    is_deleted = Farming_Operation_controller.delete_Farming_Operation(db, ID)
    if is_deleted is None:
        raise HTTPException(status_code=404, detail=f'Sample {ID} does not exist in database')
    else:
        return {'message': f'Successfully delete sample {ID}'}
